<template>
  <div
    class="grid-cell data-view"
    v-bind="layoutProps"
    :class="[selected ? 'selected' : '', customClass, entity ? '' : 'noEntity']"
    :style="boxStyle"
    :key="widget.id"
    @click.stop="selectWidget(widget)"
  >
    <container-wrapper
      :designer="designer"
      :widget="widget"
      :entityWarn="!entity"
      :parent-widget="parentWidget"
      :parent-list="parentList"
      :index-of-parent-list="indexOfParentList"
    >
      <draggable
        :list="widget.widgetList"
        v-bind="{ group: 'dragGroup', ghostClass: 'ghost', animation: 200 }"
        handle=".drag-handler"
        @end="(evt) => onGridDragEnd(evt, widget.widgetList)"
        @add="(evt) => onGridDragAdd(evt, widget.widgetList)"
        @update="onGridDragUpdate"
        :move="checkContainerMove"
      >
        <div class="controlContent">
          <el-button v-if="showAdd" type="primary" @click="add" size="mini"
            >新增</el-button
          >
          <el-button v-if="isBatchDel" @click="batchDel" size="mini"
            >删除</el-button
          >

          <div
            class="controlContentOperate"
            v-if="columnSelect || refresh || showSearch"
          >
            <el-button
              icon="el-icon-search"
              circle
              size="mini"
              v-if="showSearch"
            ></el-button>
            <el-button
              icon="el-icon-refresh"
              circle
              size="mini"
              v-if="refresh"
            ></el-button>
            <el-button
              icon="el-icon-s-operation"
              circle
              size="mini"
              v-if="columnSelect"
              @click="showColumn = true"
            ></el-button>
          </div>
        </div>
        <el-table
          :data="tableData"
          border
          size="mini"
          v-if="isBatch"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55"> </el-table-column>
          <el-table-column
            v-for="item in headData"
            :v-if="item.visible"
            :key="item.value"
            :prop="item.value"
            :label="item.label"
            :sortable="item.sort"
            :column-key="item.value"
            :filters="getFilterNameItem()"
          >
            <template slot-scope="{ row }">
              {{ item.value }}
            </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            label="操作"
            v-if="operateColumn"
            width="150"
          >
            <template slot-scope="scope">
              <el-button
                @click.native.prevent="viewRow(scope.$index, scope.row)"
                type="text"
                size="small"
              >
                查看
              </el-button>
              <el-button
                @click.native.prevent="addRow(scope.$index, scope.row)"
                type="text"
                size="small"
              >
                新增
              </el-button>
              <el-button
                @click.native.prevent="deleteRow(scope.$index, scope.row)"
                type="text"
                size="small"
              >
                移除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-table
          :data="tableData"
          border
          size="mini"
          v-else
          @cell-click="(row, column) => handleClick({ column })"
        >
          <el-table-column
            v-for="item in headData"
            :v-if="item.visible"
            :key="item.value"
            :prop="item.value"
            :label="item.label"
            :class-name="item.current ? 'cellSelected' : ''"
          >
            <template slot-scope="{ row }">
              {{ item.value }}
            </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            label="操作"
            v-if="operateColumn"
            width="150"
          >
            <template slot-scope="scope">
              <el-button
                @click.native.prevent="viewRow(scope.$index, scope.row)"
                type="text"
                size="small"
              >
                查看
              </el-button>
              <el-button
                @click.native.prevent="addRow(scope.$index, scope.row)"
                type="text"
                size="small"
              >
                新增
              </el-button>
              <el-button
                @click.native.prevent="deleteRow(scope.$index, scope.row)"
                type="text"
                size="small"
              >
                移除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          v-if="pagination"
          :style="{ textAlign: 'right' }"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="currentPage"
          :page-size="pageSize"
          layout="total, prev, pager, next"
          :total="total"
        >
        </el-pagination>
      </draggable>
      <el-drawer
        title="列显隐"
        width="850px"
        :visible.sync="showColumn"
        append-to-body
        custom-class="columnOperateDrawer"
        :before-close="beforeClose"
      >
        <div class="columnOperate">
          <el-table
            :data="initHeadData"
            border
            style="width: 100%"
            :header-contextmenu="colClick"
          >
            <el-table-column prop="label" label="列名" width="180">
            </el-table-column>
            <el-table-column prop="canAdd" label="新增" width="80">
              <template slot-scope="{ row }">
                <el-checkbox v-model="row.canAdd"></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column prop="canSearch" label="查询" width="80">
              <template slot-scope="{ row }">
                <el-checkbox v-model="row.canSearch"></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column prop="visible" label="显隐" width="80">
              <template slot-scope="{ row }">
                <el-checkbox v-model="row.visible"></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column prop="freeze" label="冻结" width="80">
              <template slot-scope="{ row }">
                <el-checkbox v-model="row.freeze"></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column prop="filter" label="过滤" width="80">
              <template slot-scope="{ row }">
                <el-checkbox v-model="row.filter"></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column prop="sort" label="排序" width="80">
              <template slot-scope="{ row }">
                <el-checkbox v-model="row.sort"></el-checkbox>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-drawer>
    </container-wrapper>
  </div>
</template>

<script>
import Draggable from "vuedraggable";
import i18n from "@/utils/i18n";
import FieldComponents from "@/components/form-designer/form-widget/field-widget/index";
import refMixinDesign from "@/components/form-designer/refMixinDesign";
import ContainerWrapper from "@/components/form-designer/form-widget/container-widget/container-wrapper";
import * as api from "@/api/modulManage/entity";

export default {
  name: "data-grid-widget",
  componentName: "DataViewWidget",
  mixins: [i18n, refMixinDesign],
  inject: ["refList"],
  components: {
    Draggable,
    ContainerWrapper,
    ...FieldComponents,
  },
  props: {
    widget: Object,
    parentWidget: Object,
    parentList: Array,
    indexOfParentList: Number,
    designer: Object,

    colHeight: {
      type: String,
      default: null,
    },
  },
  computed: {
    selected() {
      return this.widget.id === this.designer.selectedId;
    },

    customClass() {
      return this.widget.options.customClass || "";
    },
    entity() {
      return this.widget.options.entity || "";
    },
    isBatch() {
      return this.widget.options.dataViewConfig.isBatch || "";
    },
    operateColumn() {
      return this.widget.options.dataViewConfig.operateColumn || "";
    },
    showSearch() {
      return this.widget.options.dataViewConfig.showSearch || "";
    },
    showAdd() {
      return this.widget.options.dataViewConfig.showAdd || "";
    },
    pagination() {
      return this.widget.options.dataViewConfig.pagination || "";
    },
    isBatchDel() {
      return this.widget.options.dataViewConfig.isBatchDel || "";
    },
    columnSelect() {
      return this.widget.options.dataViewConfig.columnSelect || "";
    },
    refresh() {
      return this.widget.options.dataViewConfig.refresh || "";
    },

    selectEntity() {
      return this.widget.options.customClass || "";
    },
    boxStyle() {
      const initStyle = this.widget.options.initStyle || {};
      if (!initStyle) {
        return {};
      }
      const style = {
        width:
          initStyle.width && initStyle.width.indexOf("%") > -1
            ? initStyle.width
            : initStyle.width + "px",
        // height:initStyle.height&&initStyle.height.indexOf('%') > -1 ? initStyle.height : initStyle.height + 'px',
        minHeight:
          initStyle.minHeight && initStyle.minHeight.indexOf("%") > -1
            ? initStyle.height
            : initStyle.height + "px",
        backgroundColor: initStyle.backgroundColor,
        color: initStyle.color,
        margin: this.getNumber(initStyle.margin),
        padding: this.getNumber(initStyle.padding),
      };

      return style;
    },
  },
  data() {
    return {
      layoutProps: {
        span: this.widget.options.span || 12,
        offset: this.widget.options.offset || 0,
        push: this.widget.options.push || 0,
        pull: this.widget.options.pull || 0,
      },
      entityData: {},
      tableData: [],
      headData: [],
      initHeadData: [],
      selectedData: [],
      currentPage: 1,
      total: 0,
      pageSize: 10,
      showColumn: false,
    };
  },
  watch: {
    "designer.formConfig.layoutType": {
      handler(val) {
        if (this.widget.options.responsive) {
          if (val === "H5") {
            this.layoutProps.span = this.widget.options.xs || 12;
          } else if (val === "Pad") {
            this.layoutProps.span = this.widget.options.sm || 12;
          } else {
            this.layoutProps.span = this.widget.options.md || 12;
          }
        } else {
          this.layoutProps.span = this.widget.options.span || 12;
        }
      },
    },

    // 监听实体变化
    "widget.options.entity": {
      handler(val) {
        if (val) {
          this.updateTableByEntity(val);
        }
      },
    },
  },
  created() {
    this.initRefList();
    this.initLayoutProps();
    this.updateTableByEntity(this.widget.options.entity);
  },
  methods: {
    getNumber(num){
      if(Number(num) || Number(num)===0){
        return `${num}px`
      }
      if(num.indexOf(',')>-1){
        const newData = num.split(',');
        const newDataPx= newData.map(v=>(`${v}px`));
        return newDataPx.join(' ');
      }
      
      if(isNaN(Number(num))){
        return 0;
      }
      return `${num}px`
    },

    updateTableByEntity(val) {
      if (!val) {
        return;
      }
      this.designer.loadingData = true;
      try {
        api.getTypeAllAttributeByName({ typeName: val }).then((res) => {
          this.designer.loadingData = false;
          if (!res.data || !res.data.data) {
            return;
          }
          const entityData = res.data.data;
          this.designer.attrList = [...res.data.data];
          const headData = entityData.map((v) => ({
            label: v.nameCn,
            value: v.columnName,
            visible: true,
            columnType: v.columnType,
          }));
          this.headData = headData;
          this.initHeadData = [...headData];
          console.log("headData", headData);
          const keyData = headData.map((v) => v.value);
          this.tableData = [1, 2, 3, 4, 5].map((v) => {
            const newData = {};
            keyData.map((k) => (newData[k] = v));
            return newData;
          });
          this.widget.options.tableData = this.tableData;
          this.widget.options.headData = this.headData;
          console.log("this.tableData", this.tableData);

          //创建长度为5的数据
        });
      } catch (err) {
        this.designer.loadingData = false;
      }
    },
    handleClick({ column }) {
      this.headData.forEach((item) => {
        if (item.prop === column.property) {
          item.current = true;
        } else {
          item.current = false;
        }
      });
    },
    getFilterNameItem() {},
    colClick(column, e) {
    },
    filterHandler(val) {
      console.log("valval", val);
    },
    beforeClose() {
      this.headData = this.initHeadData.filter((v) => v.visible);
      this.showColumn = false;
    },
    add() {},
    batchDel() {},
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
    },
    handleSelectionChange(val) {
      this.selectedData = val;
    },
    viewRow(index, data) {
      console.log("index,data", index, data);
    },
    addRow(index, data) {
      console.log("index,data", index, data);
    },
    deleteRow(index, data) {
      console.log("index,data", index, data);
    },
    initLayoutProps() {
      if (this.widget.options.responsive) {
        let lyType = this.designer.formConfig.layoutType;
        if (lyType === "H5") {
          this.layoutProps.span = this.widget.options.xs || 12;
        } else if (lyType === "Pad") {
          this.layoutProps.span = this.widget.options.sm || 12;
        } else {
          this.layoutProps.span = this.widget.options.md || 12;
        }
      } else {
        this.layoutProps.span = this.widget.options.span;
      }
    },

    onGridDragEnd(evt, subList) {
      //
    },

    onGridDragAdd(evt, subList) {
      const newIndex = evt.newIndex;
      if (subList && subList[newIndex]) {
        this.designer.setSelected(subList[newIndex]);
      }

      this.designer.emitHistoryChange();
      this.designer.emitEvent("field-selected", this.widget);
    },

    onGridDragUpdate() {
      this.designer.emitHistoryChange();
    },

    selectWidget(widget) {
      this.designer.setSelected(widget);
    },

    checkContainerMove(evt) {
      return this.designer.checkWidgetMove(evt);
    },

    selectParentWidget() {
      if (this.parentWidget) {
        this.designer.setSelected(this.parentWidget);
      } else {
        this.designer.clearSelected();
      }
    },

    moveUpWidget() {
      this.designer.moveUpWidget(this.parentList, this.indexOfParentList);
    },

    moveDownWidget() {
      this.designer.moveDownWidget(this.parentList, this.indexOfParentList);
    },

    cloneGridCol(widget) {
      this.designer.cloneGridCol(widget, this.parentWidget);
    },

    removeWidget() {
      if (this.parentList) {
        let nextSelected = null;
        if (this.parentList.length === 1) {
          if (this.parentWidget) {
            nextSelected = this.parentWidget;
          }
        } else if (this.parentList.length === 1 + this.indexOfParentList) {
          nextSelected = this.parentList[this.indexOfParentList - 1];
        } else {
          nextSelected = this.parentList[this.indexOfParentList + 1];
        }

        this.$nextTick(() => {
          this.parentList.splice(this.indexOfParentList, 1);
          this.designer.setSelected(nextSelected);
          this.designer.emitHistoryChange();
        });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.cellSelected {
  border-color: $--color-primary !important;
  border-left: 1px solid;
  border-right: 1px solid;
  background: #ecf5ff !important;
  color: $--color-primary !important;
  font-weight: 600;
}
th.cellSelected {
  border-top: 1px solid;
}

.columnOperateDrawer {
  width: auto !important;
  .columnOperate {
    padding: 20px;
  }
}

.data-view {
  min-height: 38px;
  //margin: 6px 0;  /* 设置了margin，栅格列的offset、push、pull会失效！！ */
  padding: 10px;
  box-sizing: border-box;
  position: relative;
  border: 1px dashed rgba(170, 170, 170, 0.75);
  &.selected {
    border: 1px solid $--color-primary;
  }
  &.noEntity {
    border: 1px dashed red;
  }
  .form-widget-list {
    min-height: 46px;
  }
  .controlContent {
    margin-bottom: 20px;
    display: flex;
    .controlContentOperate {
      flex: 1;
      text-align: right;
    }
  }

  ::v-deep .el-table th.el-table__cell > .cell {
    display: inline-block;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    position: relative;
    vertical-align: middle;
    padding-left: 0.1rem;
    padding-right: 0.1rem;
    width: 100%;
    white-space: nowrap;
  }
}
</style>

